package ws.rest.books.impl;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import ws.rest.books.Book;
import ws.rest.books.BookList;
import ws.rest.books.BookService;

@Path("/books")
public class BookServiceImpl implements BookService{

	private static BookServiceImpl instance = null;
	
	private BookServiceImpl(){}
	
	public synchronized static BookServiceImpl getInstance(){
		if(instance == null)
			instance = new BookServiceImpl();
		return instance;
	}
	
	private Map<Integer,Book> bookMap = new ConcurrentHashMap<Integer, Book>();
	
	private AtomicInteger seqNumber = new AtomicInteger();
	
	@Override
	@POST
	@Consumes("application/xml")
	@Produces("application/xml")
	public Response createBook(@Context UriInfo uriInfo, Book book) {
		
		int id = seqNumber.incrementAndGet();
		book.setId(id);
		String uri_book = uriInfo.getAbsolutePath() + "/" + id;
		book.setLink(uri_book);
		bookMap.put(id, book);
		//
		String uri = "/books/" + book.getId();
		return Response.created(URI.create(uri)).build();
	}

	@Override
	@GET
	@Produces("application/xml")
	public BookList getBook() {
		BookList bl = new BookList(bookMap);
		return bl;
	}

	@Override
	@Path("{id}")
	@GET
	@Produces("application/xml")
	public Book getBook(@PathParam("id") int id) {
		final Book book = bookMap.get(id);
		if(book == null){
			throw new WebApplicationException(Response.Status.NOT_FOUND);
		}
		return book;
	}

	@Override
	@Path("{id}")
	@PUT
	@Consumes("application/xml")
	public void updateBook(@PathParam("id") int id, Book book_updated) {
		Book book = bookMap.get(id);
		if(book == null){
			throw new WebApplicationException(
					Response.Status.NOT_FOUND);
		}
		book.setTitle(book_updated.getTitle());
		book.setISBN(book_updated.getISBN());
	}

	@Override
	@Path("{id}")
	@DELETE
	public void delete(@PathParam("id") int id) {
		Book book = bookMap.get(id);
		if(book == null){
			throw new WebApplicationException(
					Response.Status.NOT_FOUND);
		}
		bookMap.remove(id);
	}


}
